﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using QuanLyThuPhiTaiLieu.Common;
using QuanLyThuPhiTaiLieu.Entity;
using QuanLyThuPhiTaiLieu.Model;

namespace QuanLyThuPhiTaiLieu.Biz
{
    public class ThamKhaoTaiLieuBiz : BaseBiz
    {
        public int SaveItem(ThamKhaoTaiLieu item)
        {
            var dbContext = new Context();
   
            dbContext.ThamKhaoTaiLieus.Add(item);
            int newId = dbContext.SaveChanges();

            return newId;
        }

        public void UpdateItem(ThamKhaoTaiLieu item)
        {
            var dbContext = new Context();
            dbContext.Entry(item).State = EntityState.Modified;
            dbContext.SaveChanges();
        }

        public List<ThamKhaoTaiLieu> ViewAll()
        {
            var dbContext = new Context();
            return (from item in dbContext.ThamKhaoTaiLieus
                    orderby item.LoaiTaiLieu ascending
                    select item).ToList();
        }

        public ThamKhaoTaiLieu LoadItem(int id)
        {
            var dbContext = new Context();
            return (from item in dbContext.ThamKhaoTaiLieus
                    where item.Id == id
                    select item).First();
        }

        public ThamKhaoTaiLieu LoadItem(string ma)
        {
            var dbContext = new Context();
            return (from item in dbContext.ThamKhaoTaiLieus
                    where item.MaTaiLieu == ma
                    select item).First();
        }

        public void RemoveItem(List<ThamKhaoTaiLieu> items)
        {
            var dbContext = new Context();
            foreach (var tailieu in items)
            {
                dbContext.ThamKhaoTaiLieus.Attach(tailieu);
                dbContext.ThamKhaoTaiLieus.Remove(tailieu);
                dbContext.Entry(tailieu).State = EntityState.Deleted;
            }

            dbContext.SaveChanges();
        }

        public List<string> GetAllLoaiTaiLieu()
        {
            var dbContext = new Context();
            return (from item in dbContext.ThamKhaoTaiLieus                    
                    select item.LoaiTaiLieu).Distinct().ToList();
        }

        public List<string> GetAllMaTaiLieu()
        {
            var dbContext = new Context();
            return (from item in dbContext.ThamKhaoTaiLieus
                    select item.MaTaiLieu).Distinct().ToList();
        }

        public List<ThamKhaoTaiLieu> SearchByName(string name)
        {
            var dbContext = new Context();
            return (from item in dbContext.ThamKhaoTaiLieus
                    where item.LoaiTaiLieu.ToLower().Contains(name.ToLower())
                    orderby item.LoaiTaiLieu ascending
                    select item).ToList();
        }
    }
}
